import React, { useState, useEffect } from 'react'
import { Space, Table, Button, Input, Modal, Form, message } from 'antd'
import {
  PoweroffOutlined,
  UserOutlined,
  CheckOutlined,
  CloseOutlined,
  ArrowUpOutlined,
  FormOutlined,
  PlusOutlined,
} from '@ant-design/icons'
import styles from '../../App.module.css'
import {
  getUsers,
  addCommUser,
  changeCommUserStatu,
  deleteCommUser,
  changeCommUser,
  filterUser,
  changeCommUserType,
} from '../../utils/http'
const { Search } = Input

const CommonUser = () => {
  const columns = [
    {
      title: '序号',
      dataIndex: 'user_id',
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '密码',
      dataIndex: 'password',
    },
    {
      title: '用户类型',
      dataIndex: 'user_type',
    },
    {
      title: '登录状态',
      dataIndex: 'user_onlinestatus',
      render: (text, record) => (
        <Space size="middle">
          <Button
            type="primary"
            size="small"
            icon={<UserOutlined />}
            disabled={text == '1' ? false : true}
          >
            在线
          </Button>
          <Button
            type="primary"
            size="small"
            icon={<UserOutlined />}
            disabled={text == '1' ? true : false}
          >
            离线
          </Button>
        </Space>
      ),
    },
    {
      title: '账号状态',
      dataIndex: 'user_other',
      render: (text, record) => (
        <Space size="middle">
          <Button
            className={styles.buttonActive}
            size="small"
            icon={<CheckOutlined />}
            onClick={() => {
              deleteCommUser({
                user_id: record.user_id,
                user_other: '1',
              }).then((res) => {
                fetchData({ pagination })
                message.success(`${record.username}用户激活成功!`)
              })
            }}
            disabled={text == '1' ? true : false}
          >
            激活
          </Button>
          <Button
            className={styles.buttonActive}
            size="small"
            icon={<CloseOutlined />}
            onClick={() => {
              deleteCommUser({
                user_id: record.user_id,
                user_other: '0',
              }).then((res) => {
                fetchData({ pagination })
                message.success(`${record.username}用户已被删除!`)
              })
            }}
            disabled={text == '0' ? true : false}
          >
            删除
          </Button>
        </Space>
      ),
    },
    {
      title: '操作',
      render: (text, record) => (
        <Space size="middle">
          <Button
            className={styles.buttonUPuser}
            size="small"
            icon={<ArrowUpOutlined />}
            onClick={() =>
              changeCommUserType({
                user_id: record.user_id,
                user_other: record.user_other,
              }).then((res) => {
                const { code, msg } = res
                if (code == 421) {
                  message.error(`${record.username}${msg}`)
                } else {
                  fetchData({ pagination })
                  message.success(`${record.username}${msg}`)
                }
              })
            }
          >
            升交管
          </Button>
          <Button
            className={styles.buttonChange}
            size="small"
            icon={<FormOutlined />}
            onClick={() =>
              showModalChange(record.user_id, record.username, record.password)
            }
          >
            修改
          </Button>
          {/* <Button
            className={styles.buttonMannege}
            size="small"
            icon={<FormOutlined />}
            // loading={loadings[1]}
            // onClick={() => enterLoading(1)}
          >
            管理
          </Button> */}
          <Button
            className={styles.buttonOutline}
            size="small"
            icon={<PoweroffOutlined />}
            // loading={loadings[1]}
            onClick={() => {
              if (record.user_onlinestatus == '0') {
                message.error(`${record.username}用户未上线`)
              } else {
                changeCommUserStatu({
                  user_id: record.user_id,
                  user_onlinestatus: '0',
                }).then((res) => {
                  fetchData({ pagination })
                  message.success(`${record.username}用户已被强制下线`)
                })
              }
            }}
          >
            下线
          </Button>
        </Space>
      ),
    },
  ]
  const [commuser, setCmmuser] = useState([])
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 8,
  })
  // const [selectedRowKeys, setSelectedRowKeys] = useState([])
  //获取普通用户信息
  const fetchData = (params = {}) => {
    getUsers(params)
      .then((res) => {
        //普通用户赋值
        setCmmuser(res.result.data),
          //每页记录条数赋值
          setPagination({
            ...params.pagination,
            total: res.result.total,
          })
      })
      .catch((err) => {
        console.log('错误信息:', err)
      })
  }
  //换页跳转
  const handleTableChange = (newPagination, filters, sorter) => {
    fetchData({
      sortField: sorter.field,
      sortOrder: sorter.order,
      pagination: newPagination,
      ...filters,
    })
  }
  //查询搜索
  const onSearch = (value) => {
    if (value) {
      filterUser({
        current: 1,
        pageSize: 8,
        filterContent: value,
      }).then((res) => {
        //如果查询存在数据,那么显示数据
        if (res.result.data.length >= 1) {
          setCmmuser(res.result.data),
            //每页记录条数赋值
            setPagination({
              ...pagination,
              total: res.result.total,
            })
        } else {
          message.error(`${'没有找到该用户!'}`)
        }
      })
    } else {
      message.error(`${'请输入用户名!'}`)
    }
  }
  //添加用户弹窗
  const [visible, setVisible] = useState(false)
  //修改用户弹窗
  const [visibleChange, setVisibleChange] = useState(false)
  const [disabled, setDisabled] = useState(false)
  const [form] = Form.useForm()
  //获取表中数据
  const userName = Form.useWatch('username', form)
  const passWord = Form.useWatch('password', form)
  const [changeId, setchangeId] = useState()
  const showModal = () => {
    setVisible(true)
  }
  const onFinish = (e) => {
    console.log(e)
  }
  const onFinishFailed = () => {
    console.log(e)
  }
  //添加提交
  const submit = () => {
    //表单验证是否通过
    form
      .validateFields()
      .then(() => {
        //通过,则发送请求添加用户
        addCommUser({ username: userName, password: passWord }).then((res) => {
          const { code, msg } = res
          if (code == 202) {
            message.success(`${msg}`)
            //清除表单
            form.resetFields()
            setVisible(false)
            fetchData({
              pagination,
            })
          } else {
            message.error(`${msg}`)
          }
        })
      })
      .catch(() => {
        //未通过
        console.log('验证未通过')
      })
  }
  //提交取消
  const handleCancel = () => {
    form.resetFields()
    setVisible(false)
    setVisibleChange(false)
  }
  //修改用户名和密码
  const showModalChange = (id, u, p) => {
    form.setFieldsValue({
      username: u,
      password: p,
    })
    setVisibleChange(true)
    setchangeId(id)
  }
  //添加提交
  const submitChange = () => {
    //表单验证是否通过
    form
      .validateFields()
      .then(() => {
        //通过,则发送请求添加用户
        changeCommUser({
          user_id: changeId,
          username: userName,
          password: passWord,
        }).then((res) => {
          const { code, msg } = res
          if (code == 205) {
            message.success(`${msg}`)
            //清除表单
            form.resetFields()
            setVisibleChange(false)
            fetchData({
              pagination,
            })
          }
        })
      })
      .catch(() => {
        //未通过
        console.log('验证未通过')
      })
  }
  //监听输入框事件,查询后输入为空则返回
  const onChangeInput = (e) => {
    e.target.value == ''
      ? fetchData({
          pagination,
        })
      : ''
  }
  useEffect(() => {
    fetchData({
      pagination,
    })
  }, [])
  return (
    <div className={styles.common}>
      <header className={styles.header}>
        <span>普通用户账户管理</span>
        <Search
          placeholder="请输入用户名"
          style={{
            width: 300,
            marginLeft: 20,
          }}
          onSearch={onSearch}
          onChange={onChangeInput}
          enterButton
        />
        <Button
          className={styles.add}
          type="primary"
          icon={<PlusOutlined />}
          onClick={showModal}
        >
          添加用户
        </Button>
        <Modal
          footer={null}
          title={
            <div
              style={{
                width: '100%',
                cursor: 'move',
              }}
              onMouseOver={() => {
                if (disabled) {
                  setDisabled(false)
                }
              }}
              onMouseOut={() => {
                setDisabled(true)
              }}
            >
              添加普通用户
            </div>
          }
          visible={visible}
          onCancel={handleCancel}
        >
          <Form
            name="basic"
            labelCol={{
              span: 4,
            }}
            wrapperCol={{
              span: 16,
            }}
            initialValues={{
              remember: true,
            }}
            form={form}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="用户名"
              name="username"
              rules={[
                {
                  required: true,
                  message: '请输入用户名!',
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="密码"
              name="password"
              rules={[
                {
                  required: true,
                  message: ' 请输入密码!',
                },
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              wrapperCol={{
                offset: 4,
                span: 16,
              }}
            >
              <Button
                type="primary"
                onClick={submit}
                className={styles.submitBtn}
              >
                提交
              </Button>
              <Button type="primary" onClick={handleCancel}>
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </header>
      <Table
        columns={columns}
        dataSource={commuser}
        //每一列的key
        rowKey={(record) => record.user_id}
        pagination={pagination}
        onChange={handleTableChange}
        bordered
      />
      <Modal
        footer={null}
        title={
          <div
            style={{
              width: '100%',
              cursor: 'move',
            }}
            onMouseOver={() => {
              if (disabled) {
                setDisabled(false)
              }
            }}
            onMouseOut={() => {
              setDisabled(true)
            }}
          >
            修改用户名和密码
          </div>
        }
        visible={visibleChange}
        onCancel={handleCancel}
      >
        <Form
          name="basic"
          labelCol={{
            span: 4,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          form={form}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              {
                required: true,
                message: '请输入用户名!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: ' 请输入密码!',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 4,
              span: 16,
            }}
          >
            <Button
              type="primary"
              onClick={submitChange}
              className={styles.submitBtn}
            >
              提交
            </Button>
            <Button type="primary" onClick={handleCancel}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default CommonUser
